/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aaron.platform.view;

import com.aaron.platform.entity.ItscUserInfo;
import com.aaron.platform.exceptions.UserSessionException;
import com.aaron.platform.service.UserSession;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.el.VariableResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;

/**
 * JSF工具类
 * @author chenzhuohua
 */
public class FacesUtil {

    private static final Logger log = Logger.getLogger(FacesUtil.class);

    private static ResourceBundle resource;

    private static ClassLoader getCurrentClassLoader(Object object) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader == null) {
            loader = object.getClass().getClassLoader();
        }
        return loader;
    }

    public static String getString(String messaggeId, Object... params) {

        if (resource == null) {
            // 取得应用程序代表对象
            Application application = FacesContext.getCurrentInstance().getApplication();

            // 取得信息文件主名称
            String bundleName = application.getMessageBundle();

            // 取得当前 Locale 对象
            Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();

            // 取得信息绑定 ResourceBundle 对象
            resource = ResourceBundle.getBundle(bundleName, locale, getCurrentClassLoader(params));

        }

        String message = null;

        // 获取字符串
        try {
            message = resource.getString(messaggeId);
        } catch (MissingResourceException mre) {
            log.error("key:" + messaggeId + " not found.");
        }

        if (message != null && params != null) {
            message = MessageFormat.format(message, params);
        }

        return message;
    }

    public static FacesMessage getMessage(FacesMessage.Severity severityLevel,
            String messageId, Object... params) {
        return new FacesMessage(severityLevel, getString(messageId, params), null);
    }

    public static void addErrorMessage(String clientId, String messageId, Object... params) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.addMessage(clientId, getMessage(FacesMessage.SEVERITY_ERROR, messageId, params));
    }

    public static void addErrorMessage(String clientId, int errCode, Object... params) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        StringBuffer sBuffer = new StringBuffer();
        sBuffer.append("er_code_")
                .append(errCode);
        facesContext.addMessage(clientId, getMessage(FacesMessage.SEVERITY_ERROR, sBuffer.toString(), params));
    }

    public static void addInfoMessage(String clientId, String messageId, Object... params) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.addMessage(clientId, getMessage(FacesMessage.SEVERITY_INFO, messageId, params));
    }
   
    public static void addWarnMessage(String clientId, String messageId, Object... params) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.addMessage(clientId, getMessage(FacesMessage.SEVERITY_WARN, messageId, params));
    }

    public static void addFatalMessage(String clientId, String messageId, Object... params) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.addMessage(clientId, getMessage(FacesMessage.SEVERITY_FATAL, messageId, params));
    }

    public static String getClientIpAddress() {
       try {
        FacesContext fc = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest)fc.getExternalContext().getRequest();
        return request.getRemoteAddr();
       } catch (Exception e) {
           log.error("Fail to get client IP address.", e);
           return null;
       }
    }

    public static HttpSession getClientSession() throws UserSessionException {
       try {
        FacesContext fc = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession)fc.getExternalContext().getSession(true);
        return session;
       } catch (Exception e) {
           log.error("Fail to get client session.", e);
           throw new UserSessionException();
       }
    }
    
    public static ItscUserInfo getCurrentUser() throws UserSessionException {
       HttpSession httpSession = getClientSession();
       UserSession userSession = (UserSession) httpSession.getAttribute("user");
       return userSession.getUserInfo();
    }

    public static Object getManagedBean(String beanName) {
        FacesContext context =FacesContext.getCurrentInstance();
        VariableResolver variableResolver =context.getApplication().getVariableResolver();
        Object bean = (Object)variableResolver.resolveVariable(context, beanName);
        return bean;
    }
}
